package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 菜单服务
 */

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;

    //新增菜单项
    @Override
    public void add(Menu menu) {
        menuDao.add(menu);
    }

    //分页查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer pageSize = queryPageBean.getPageSize();
        Integer currentPage = queryPageBean.getCurrentPage();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<Menu> page = menuDao.findByCondition(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    //删除
    @Override
    public void delete(Integer id) {
        menuDao.deleteById(id);
    }

    //根据id回显
    @Override
    public Menu findById(Integer id) {
        return menuDao.findById(id);
    }

    //编辑
    @Override
    public void edit(Menu menu) {
        menuDao.edit(menu);
    }

    //查询所有
    @Override
    public List<Menu> findAll() {
        List<Menu> menuList = menuDao.findAll();
        List<Menu> menus = new ArrayList<>();
        for (Menu menu : menuList) {
            if (menu.getLevel() == 1) {
                menus.add(menu);
                List<Menu> children = menuDao.findChildren(menu.getId());
                for (Menu child : children) {
                    menus.add(child);
                }
            }
        }
        return menus;
    }

    //查询子菜单
    public List findUserMenuRole(Integer id) {
        return menuDao.findUserMenuRole(id);
    }

}